//引入 axios 
import axios from 'axios'
import constantJs from '../assets/js/constant'
import { Message } from 'element-ui'

//设置请求的基础路径和字符集
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.baseURL = '/wtf'


//设置请求拦截器
axios.interceptors.request.use(function (config) {
  //判断请求拦截器中是否带有token
  let token = localStorage.getItem(constantJs.authTokenHeader)
  if (token) {
    config.headers[constantJs.authTokenHeader] = token
  }
  return config
})

// 响应拦截器
axios.interceptors.response.use(response => {
    const httpStatus = response.status
      const result = response.data;
      const code = result.code;
      if(code === undefined){
        return response;
      }
      if(code === 0){
        return result;
      } else if (code === 401){
        const msg = result.msg;
        location.href = '/login';
        Message({ message: msg, type: 'error',duration: 5 * 1000 })
        return Promise.reject(new Error(msg))
      } else {
        const msg = result.msg;
        Message({ message: msg, type: 'error',duration: 5 * 1000  })
        return Promise.reject(new Error(msg))
      }
},error => {
  let { message } = error;
  if (message == "Network Error") {
    message = "后端接口连接异常";
  } else if (message.includes("timeout")) {
    message = "系统接口请求超时";
  } else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常";
  }
  Message({ message: message, type: 'error', duration: 5 * 1000 })
  return Promise.reject(error)
})


export default axios